"""
系统操作助手主应用
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import uvicorn
from loguru import logger

from app.core.config import settings
from app.models.base import create_tables
from app.api.chat import router as chat_router
from app.api.documents import router as documents_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("🚀 启动系统操作助手...")
    
    # 创建数据库表
    try:
        create_tables()
        logger.info("✅ 数据库表创建成功")
    except Exception as e:
        logger.error(f"❌ 数据库表创建失败: {e}")
    
    # 调试：检查环境变量加载
    from app.core.config import check_env_loading
    check_env_loading()

    # 检查配置
    if not settings.openai_api_key:
        logger.warning("⚠️  OpenAI API密钥未配置，AI功能将不可用")
        logger.info("💡 配置步骤：")
        logger.info("   1. 复制 .env.example 为 .env")
        logger.info("   2. 在 .env 文件中设置 OPENAI_API_KEY")
        logger.info("   3. 重启服务")
    else:
        logger.info("✅ OpenAI API密钥已配置")

    if not settings.embedding_api_key:
        logger.warning("⚠️  嵌入模型API密钥未配置，知识库搜索功能将不可用")
    else:
        logger.info("✅ 嵌入模型API密钥已配置")

    # 确保必要目录存在
    from app.core.config import ensure_directories
    ensure_directories()
    logger.info("✅ 目录结构检查完成")

    # 预先初始化知识库服务（单例模式）
    try:
        from app.services.knowledge_service import KnowledgeService
        KnowledgeService()
        logger.info("✅ 知识库服务初始化完成")
    except Exception as e:
        logger.warning(f"⚠️ 知识库服务初始化失败: {e}")
    
    yield
    
    # 关闭时执行
    logger.info("🛑 系统操作助手关闭")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="基于大语言模型的智能系统操作指导助手",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 临时允许所有源，用于开发环境
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(chat_router)
app.include_router(documents_router)


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "欢迎使用系统操作助手",
        "app_name": settings.app_name,
        "version": settings.app_version,
        "status": "running"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    try:
        # 检查数据库连接
        from app.models.base import SessionLocal
        db = SessionLocal()
        try:
            from sqlalchemy import text
            db.execute(text("SELECT 1"))
            db_status = "healthy"
        except Exception as e:
            db_status = f"error: {str(e)}"
        finally:
            db.close()
        
        # 检查知识库
        try:
            from app.services.knowledge_service import KnowledgeService
            knowledge_service = KnowledgeService()  # 现在使用单例，不会重复初始化
            kb_stats = knowledge_service.get_collection_stats()
            kb_status = "healthy"
        except Exception as e:
            kb_status = f"error: {str(e)}"
            kb_stats = {}
        
        return {
            "status": "healthy",
            "database": db_status,
            "knowledge_base": kb_status,
            "knowledge_base_stats": kb_stats,
            "app_version": settings.app_version
        }
        
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "status": "unhealthy",
                "error": str(e)
            }
        )


@app.get("/api/info")
async def get_app_info():
    """获取应用信息"""
    return {
        "app_name": settings.app_name,
        "version": settings.app_version,
        "debug": settings.debug,
        "features": {
            "ai_chat": True,
            "document_processing": True,
            "knowledge_base": True
        },
        "supported_formats": [".pdf", ".txt", ".md", ".docx"],
        "ai_model": settings.openai_model
    }


@app.exception_handler(404)
async def not_found_handler(request, exc):
    """404错误处理"""
    return JSONResponse(
        status_code=404,
        content={
            "error": "接口不存在",
            "message": f"请求的路径 {request.url.path} 不存在",
            "available_endpoints": [
                "/",
                "/health",
                "/api/info",
                "/api/chat/send",
                "/api/documents/process"
            ]
        }
    )


@app.exception_handler(500)
async def internal_error_handler(request, exc):
    """500错误处理"""
    logger.error(f"内部服务器错误: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "error": "内部服务器错误",
            "message": "服务器遇到了一个错误，请稍后重试"
        }
    )


def main():
    """主函数"""
    logger.info(f"启动 {settings.app_name} v{settings.app_version}")
    logger.info(f"调试模式: {settings.debug}")
    logger.info(f"监听地址: {settings.host}:{settings.port}")
    
    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )


if __name__ == "__main__":
    main()
